#include "StdAfx.h"
#include "DayTimeTable.h"


DayTimeTable::DayTimeTable(void)
    : m_time(0)
{
    for (int i=0; i<TABLE_SIZE; i++)
        m_tbl[i] = FALSE;
}


DayTimeTable::~DayTimeTable(void)
{
}


BOOL DayTimeTable::Allowed(int idx)
{
    BOOL b = FALSE;
    if (idx >= 0 && idx < TABLE_SIZE)
        b = m_tbl[idx];
    return b;
}


void DayTimeTable::Allow(int idx, BOOL b)
{
    m_tbl[idx] = b;
}


int DayTimeTable::ReadConfig(const BYTE* config)
{
    // transform a bit stream in a BYTE stream
    DWORD* pConf = (DWORD*)config;
    DWORD mask = 1;
    for (int i=0; i<TABLE_SIZE; i++)
    {
        m_tbl[i] = (*pConf & mask) != 0;
        mask <<= 1;
        if (mask == 0)
        {
            pConf++;
            mask = 1;
        }
    }
    m_time = *(long*)(config+sizeof(DWORD64));
    return (sizeof(DWORD64)+sizeof(long));
}


int DayTimeTable::SaveConfig(BYTE* config)
{
    // transform BYTE stream in bit stream

    // start with a cleared stream
    *(DWORD64*)config = 0;
    DWORD* pConf = (DWORD*)config;
    unsigned long mask = 1;
    for (int i=0; i<TABLE_SIZE; i++)
    {
        if (m_tbl[i] != 0)
        {
            *pConf |= mask;
        }
        mask <<= 1;
        if (mask == 0)
        {
            pConf++;
            mask = 1;
        }
    }

    *(long*)(config+sizeof(DWORD64)) = m_time;
    return (sizeof(DWORD64)+sizeof(long));
}


UserStatus DayTimeTable::HasToStop(SYSTEMTIME& st)
{
    int h = st.wHour;
    int m = st.wMinute;
    int idx = (h*2);
    if (m >= 30)
        idx++;
    if (m_tbl[idx])
        return CanContinue;
    else
        return OutOfSchedule;
}

int DayTimeTable::TimeRemainsSchedule(SYSTEMTIME& st)
{
    int h = st.wHour;
    int m = st.wMinute;
    int idx = (h*2);
    if (m >= 30)
        idx++;
    while (idx<48 && m_tbl[idx])
        idx++;
    int min = ((idx/2) - h) * 60;
    if (idx&1)
        min += 30;
    min -= m;
    return min;
}
